#include "sdl_binding.h"

/*
 * class sdl_bindstate
 */
sdl_bindstate::sdl_bindstate()
{
    key = -1;
    state = false;
}

sdl_bindstate::sdl_bindstate(const int & k) : key(k)
{
    state = false;
}

sdl_bindstate::sdl_bindstate(const SDLKey & k) : key(int(k))
{
    state = false;
}

sdl_bindstate::sdl_bindstate(const std::string & k)
{
    std::map<std::string, int> kmap;

    for (int i = SDLK_FIRST; i <= SDLK_LAST; i++)
        kmap[std::string(SDL_GetKeyName(SDLKey(i)))] = i;

    key = kmap[k];

    state = false;
}

sdl_bindstate::sdl_bindstate(const char * k)
{
    std::map<std::string, int> kmap;

    for (int i = SDLK_FIRST; i <= SDLK_LAST; i++)
        kmap[std::string(SDL_GetKeyName(SDLKey(i)))] = i;

    key = kmap[std::string(k)];

    state = false;
}


///operator = przypisuje do klawisza

void sdl_bindstate::operator=(const int & k)
{
    key = k;
    state = false;
}

///przypisanie za pomocą nazwy klawisza

void sdl_bindstate::operator=(const std::string & k)
{
    std::map<std::string, int> kmap;

    for (int i = SDLK_FIRST; i <= SDLK_LAST; i++) {
        kmap[std::string(SDL_GetKeyName(SDLKey(i)))] = i;
    }

    key = kmap[k];

    state = false;
}

void sdl_bindstate::operator=(const char * k)
{
    std::map<std::string, int> kmap;

    for (int i = SDLK_FIRST; i <= SDLK_LAST; i++)
        kmap[std::string(SDL_GetKeyName(SDLKey(i)))] = i;

    key = kmap[std::string(k)];

    state = false;
}

sdl_bindstate::operator bool()
{
    return state;
}

/*
 * class binding;
 */

sdl_binding::sdl_binding() : sdl_layer(2, "binding")
{
}

///wyrzuca kod SDL klawisza o nazwie n

int sdl_binding::get_key_from_name(const std::string & n)
{
    std::map<std::string, int> kmap;

    for (int i = SDLK_FIRST; i <= SDLK_LAST; i++)
        kmap[std::string(SDL_GetKeyName(SDLKey(i)))] = i;

    return kmap[n];

}

bool sdl_binding::operator()(const std::string & name)
{
    return kmap[name].state;
}

void sdl_binding::update()
{
    if (give<sdl_input > ())
        for (std::map<std::string, sdl_bindstate>::iterator i = kmap.begin(); i != kmap.end(); i++)
            kmap[(*i).first].state = give<sdl_input > ()->keyboard[(*i).second.key];
}

sdl_bindstate & sdl_binding::operator[](const std::string & name)
{
    return kmap[name];
}
